<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" class="preview" v-if="avatar"/>
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-else/>

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" @change="getImage" style="display:none" accept="image/*" ref="upFile">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.upFile.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadAvatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data(){
    return {
      avatar:''
    }
  },
  methods:{
    getImage(e){
      console.log(e);
      // 获取文件选择列表
      const fileList = e.target.files
      if(fileList.length > 0){
        // 选择了图片的话
        // 创建了reader实例对象
        const reader = new FileReader()
        // 将readAsDataUrl转化为base64的字符串
        reader.readAsDataURL(fileList[0])
        // load事件监听 转化完成时触发,通过reader.result获取结果
        reader.onload = () => {
          // 细节使用箭头函数,避免this.avatar获取不到data里的数据
          console.log(reader.result);
          this.avatar = reader.result
        }
        }else{
          // 如果没有选中
          this.avatar = ''
      }
    },
    async uploadAvatar(){
      const {data:res} = await this.$http.patch('/my/update/avatar',{
        avatar: this.avatar
      })
      if(res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 清空avatar数据
      this.avatar = ''
      // 重新获取用户信息
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
